package com.schoolhelper.login.mapper;

import com.schoolhelper.login.domain.User;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;

@Mapper
public interface UserMapper {
    @Select("SELECT id, username, account, password, school_num as schoolNum, school_name as schoolName, " +
            "major, grade, class_num as classNum, email, phone, address, avatar, role, status, " +
            "create_time as createTime, update_time as updateTime, last_login_time as lastLoginTime, balance " +
            "FROM users WHERE account = #{account}")
    User findByAccount(String account);

    @Select("SELECT id, username, account, password, school_num as schoolNum, school_name as schoolName, " +
            "major, grade, class_num as classNum, email, phone, address, avatar, role, status, " +
            "create_time as createTime, update_time as updateTime, last_login_time as lastLoginTime, balance " +
            "FROM users WHERE id = #{userId}")
    User findByUserId(Long userId);

    @Select("SELECT id, username, account, password, school_num as schoolNum, school_name as schoolName, " +
            "major, grade, class_num as classNum, email, phone, address, avatar, role, status, " +
            "create_time as createTime, update_time as updateTime, last_login_time as lastLoginTime, balance " +
            "FROM users WHERE username = #{username}")
    User findByUsername(String username);

    @Insert("INSERT INTO users( username,account, password, phone, role, status, create_time, update_time, balance) " +
            "VALUES(#{username},#{account}, #{password}, #{phone}, #{role}, #{status}, #{createTime}, #{updateTime}, #{balance})")
    int userRegiste(User user);
    
    @Update("<script>" +
            "UPDATE users SET " +
            "<if test='username != null'>username = #{username}, </if>" +
            "<if test='schoolNum != null'>school_num = #{schoolNum}, </if>" +
            "<if test='schoolName != null'>school_name = #{schoolName}, </if>" +
            "<if test='major != null'>major = #{major}, </if>" +
            "<if test='grade != null'>grade = #{grade}, </if>" +
            "<if test='classNum != null'>class_num = #{classNum}, </if>" +
            "<if test='email != null'>email = #{email}, </if>" +
            "<if test='address != null'>address = #{address}, </if>" +
            "<if test='avatar != null'>avatar = #{avatar}, </if>" +
            "update_time = #{updateTime} " +
            "WHERE id = #{id}" +
            "</script>")
    int updateUserProfile(User user);
    
    @Update("UPDATE users SET last_login_time = NOW() WHERE id = #{userId}")
    int updateLastLoginTime(Long userId);
}